package com.orange.notificationsummary.event.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.CallLog.Calls;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;

import com.orange.notificationsummary.R;
import com.orange.notificationsummary.event.pil.defaultimpl.BaseEvent;
import com.orange.notificationsummary.event.pil.defaultimpl.MissCallEvent;
import com.orange.notificationsummary.utils.Constants;
import com.orange.notificationsummary.utils.Constants.EventType;
import com.orange.notificationsummary.utils.EventLSWidgetUtils;
import com.orange.notificationsummary.utils.LogHelper;
import com.orange.notificationsummary.utils.VipUtils;

public class MissedCallDBHelper {
	private static final String	TAG				= "MissedCallDBHelper";

	private static final String	CALL_UNNEW_TYPE	= "0";

	public static int updateMissCallStatusByNumber(Context context,
			String columnName, String columnValue) {
		int updateRslt = 0;

		if (!TextUtils.isEmpty(columnValue)) {

			ContentValues cv = new ContentValues(1);
			cv.put(Calls.NEW, CALL_UNNEW_TYPE);

			updateRslt = context.getContentResolver().update(Calls.CONTENT_URI,
					cv, columnName + "=?", new String[] { columnValue });
		}
		return updateRslt;
	}

	/**
	 * get missed call info list
	 * 
	 * @return
	 */
	public static List<BaseEvent> getAllMissedCallEvent(Context context) {
		List<BaseEvent> missedCallEvents = null;
		Map<String, Bitmap> contactPhotoMap = new HashMap<String, Bitmap>();
		Map<String, Integer> numberCountMap = new HashMap<String, Integer>();
		Map<String, String> numberTypeMap = new HashMap<String, String>();
		Map<String, String> contactDisplayNameMap = new HashMap<String, String>();
		Cursor c = null;
		try {
			c = queryMissedCallInfo(context);
			if (c != null && c.moveToFirst()) {
				missedCallEvents = new ArrayList<BaseEvent>();
				while (!c.isAfterLast()) {
					BaseEvent call = new MissCallEvent(context);
					call.id = c.getInt(0);
					call.evnet_number = c.getString(1);
					call.event_date = c.getLong(2);
					if (EventLSWidgetUtils.getEventPreviewSetting(context)) {
						call.evnet_number_type = "";
					} else {
						call.evnet_number_type = NotificationDBHelper
								.getNumberTypeByMap(context, call.evnet_number,
										numberTypeMap);
					}
					call.event_type_name = context.getResources().getString(
							R.string.missed_call_event_name);
					call.event_type = EventType.MISSCALL_UPDATE;
					call.event_type_image = context.getResources().getDrawable(
							R.drawable.icon_missed_call_24);
					call.contacts_id = NotificationDBHelper.getContactId(
							context, call.evnet_number);
					if (call.contacts_id != null) {
						call.contacts_image = NotificationDBHelper
								.getContactPhotoByContactId(context,
										call.contacts_id, contactPhotoMap);
						call.isInContacts = true;
						call.phoneNumberCount = NotificationDBHelper
								.getContactNumberCountByMap(context,
										call.contacts_id, numberCountMap);
						call.evnet_name = NotificationDBHelper
								.getDisplayNameByMap(context, call.contacts_id,
										contactDisplayNameMap);
					}
					call.isVip = VipUtils.isVip(context, call.contacts_id);
					missedCallEvents.add(call);
					c.moveToNext();
				}
				c.close();
			}
		} catch (Exception e) {
			LogHelper.e(TAG, "getAllMissedCallEvent. ", e);
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return missedCallEvents;
	}

	public static Cursor queryMissedCallInfo(Context context) {
		Cursor c = null;
		if (EventLSWidgetUtils.isPackageExist(context,
				Constants.PKG_NOTIFICATION_SUMMARY)
				&& EventLSWidgetUtils.getNotifictionTypesIsChecked(context,
						Constants.KEY_WIDGET_EVENT_DETAIL_MISSED_CALL)) {
			String[] projection = new String[] { Calls._ID, Calls.NUMBER,
					Calls.DATE, Calls.CACHED_NAME, Calls.CACHED_NUMBER_TYPE,
					Calls.CACHED_NUMBER_LABEL };

			String selection = Calls.TYPE + "=" + Calls.MISSED_TYPE + " and "
					+ Calls.NEW + " =1";
			String sortOrder = Calls.DATE + " desc";

			c = context.getContentResolver().query(Calls.CONTENT_URI,
					projection, selection, null, sortOrder);
		}
		return c;
	}

	// get MissCalls Ids which have the same phoneNumber
	public static String[] getIdsByNumber(String phoneNumber, Context context) {
		List<BaseEvent> misscalls = getAllMissedCallEvent(context);
		List<String> ids = new ArrayList<String>();
		for (BaseEvent missCall : misscalls) {
			if (PhoneNumberUtils.compare(missCall.evnet_number, phoneNumber)) {
				ids.add(String.valueOf(missCall.id));
			}
		}
		return ids.toArray(new String[ids.size()]);
	}

	/**
	 * insert call log data
	 * 
	 * @param context
	 * @param missedCallInfo
	 * @return
	 */
	public static boolean insertCallLog(Context context,
			BaseEvent missedCallInfo) {
		ContentValues cv = new ContentValues();
		cv.put("number", missedCallInfo.evnet_number);
		cv.put("date", missedCallInfo.event_date);
		cv.put("duration", 0);
		cv.put("type", 3);
		cv.put("new", 1);
		Uri uri = null;
		try {
			String where = " number=? and date=? ";
			Cursor c = context.getContentResolver().query(
					android.provider.CallLog.Calls.CONTENT_URI,
					null,
					where,
					new String[] { missedCallInfo.evnet_number,
							String.valueOf(missedCallInfo.event_date) }, null);
			if (c != null && c.getCount() == 0) {
				uri = context.getContentResolver().insert(
						android.provider.CallLog.Calls.CONTENT_URI, cv);
				
				// 20120214. close the cursor.
				c.close();
			}
		} catch (Exception e) {
			LogHelper.e(TAG, "insertCallLog. ", e);
			return false;
		}
		return uri != null ? true : false;
	}
}
